package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApLikesBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.model.article.dtos.UpdateArticleMess;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.common.constants.ArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
@Slf4j
public class ApLikesBehaviorServiceImpl extends ServiceImpl<ApLikesBehaviorMapper, ApLikesBehavior>
        implements ApLikesBehaviorService {

    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;

    @Autowired
    KafkaTemplate kafkaTemplate;

    /**
     * 点赞/取消点赞
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(LikesBehaviorDto dto) {
        // 参数检查
        if (dto==null || dto.getArticleId()==null
                || (dto.getOperation()<0 || dto.getOperation()>1)
                ||(dto.getType()<0 || dto.getType()>2) ){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //1 查询行为实体
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApBehaviorEntry behaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), null);
        if (behaviorEntry == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //2 保存点赞
        ApLikesBehavior apLikesBehavior =getOne(Wrappers.<ApLikesBehavior>lambdaQuery()
                .eq(ApLikesBehavior::getArticleId,dto.getArticleId() )
                .eq(ApLikesBehavior::getEntryId, behaviorEntry.getId())
                .eq(ApLikesBehavior::getType, dto.getType())
        );

        // 取消点赞，无数据
        if (apLikesBehavior == null && dto.getOperation().equals(ApLikesBehavior.Operation.CANCEL.getCode())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"暂无点赞");
        }
        // 重复点赞
        if (apLikesBehavior!=null && apLikesBehavior.getOperation().intValue()==0
                &&  dto.getOperation().equals(ApLikesBehavior.Operation.LIKE.getCode())){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"无需重复点赞");
        }

        // 点赞后发消息（数据源） kafka Stream
        if (dto.getOperation() == 0) {
            UpdateArticleMess mess = new UpdateArticleMess();
            mess.setType(UpdateArticleMess.UpdateArticleType.LIKES);
            mess.setArticleId(dto.getArticleId());
            mess.setAdd(3);
            kafkaTemplate.send(ArticleConstants.HOTARTICLE_SCORE_INPUT_TOPIC, JSON.toJSONString(mess));

            log.info("like mess:{}", mess);
        }





        // 点赞
        if (apLikesBehavior == null && dto.getOperation().equals(ApLikesBehavior.Operation.LIKE.getCode())) {

            apLikesBehavior = new ApLikesBehavior();
            apLikesBehavior.setOperation(dto.getOperation());
            apLikesBehavior.setCreatedTime(new Date());
            apLikesBehavior.setType(dto.getType());
            apLikesBehavior.setArticleId(dto.getArticleId());
            apLikesBehavior.setEntryId(behaviorEntry.getId());
            save(apLikesBehavior);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

        } else { // 取消点赞
            apLikesBehavior.setOperation(dto.getOperation());
            updateById(apLikesBehavior);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

    }
}
